// pages/qrcode/qrcode.js
let app = getApp();
let request = require("../../utils/request.js"); //封装的request请求
let timeStamp = require("../../utils/time");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    agreementVip: true,
    userInfo: {},
    parkId: "",
    channelCode: "",
    orderState: false,
    orderInfo: {},
    buttonState: false,
    showLogin: true,
    unpaidOrders: false, //待支付弹窗
    totalTime: "", //停车时长
  },

  /**
   * 生命周期函数--监听页面加载
   * parkId=1475359927982772226&channelCode=13
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      parkId: options.parkId,
      channelCode: options.channelCode,
    });
    this.getCode();

    let phoneNumber = wx.getStorageSync("phoneNumber");
    if (phoneNumber) {
      this.setData({
        showLogin: false,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 用户协议弹窗
   */
  showAgreement(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      agreementShow: true,
      agreementType: type,
    });
  },
  /**
   * 关闭用户协议弹窗
   */
  showAgreementClose() {
    this.setData({
      agreementShow: false,
    });
  },
  /**
   * 同意协议按钮事件
   */
  showAgreementCloseEvent(e, a) {
    let agreement = e.detail;
    this.setData({
      agreementVip: agreement,
    });
  },
  //关闭订单信息
  onClosePopup() {
    let _this = this;
    wx.showModal({
      title: "警告",
      content: "关闭后，请重新授权",
      confirmText: "关闭",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          _this.setData({
            orderState: false,
          });
        } else {
          _this.setData({
            orderState: true,
          });
          console.log("取消");
        }
      },
    });
  },
  // 关闭待支付订单
  onCloseOrders() {
    this.setData({
      unpaidOrders: false,
    });
  },
  /**
   * 支付
   */
  payment() {
    let _this = this;
    let orderData = this.data.orderInfo;
    //  支付垫付停车费
    let params = {
      totalAmount: orderData.paidAmount, //实付金额
      tradeRecordId: orderData.id, // 订单id
    };
    request
      .http("/order/info-trade-record/pay-behalf", "POST", params, 0)
      .then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          let orderCode = res.data.data.orderCode;
          //支付
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp, // 时间戳，必填（后台传回）
            nonceStr: res.data.data.nonceStr, // 随机字符串，必填（后台传回）
            package: res.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
            signType: "MD5", // 签名算法，非必填，（预先约定或者后台传回）
            paySign: res.data.data.paySign, // 签名 ，必填 （后台传回）
            success: function (res) {
              // 成功后的回调函数
              wx.showToast({ title: "支付成功" });
              setTimeout(function () {
                _this.setData({ orderState: false });
              }, 2000);
            },
            fail(res) {
              console.log(res);
            },
          });
        } else {
          wx.showToast({ title: res.data.desc });
        }
      });
  },

  // 获取手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      console.log(e);
      this.setData({
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
      });
      this.getPhoneNum();
    } else {
      wx.showModal({
        title: "警告",
        content: "您点击了拒绝授权，将无法进入开闸，请授权!!!",
        showCancel: false,
        confirmText: "返回授权",
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击了“返回授权”");
          }
        },
      });
    }
  },

  // 获取code
  getCode() {
    wx.login({
      success: (res) => {
        this.setData({
          code: res.code,
        });
      },
    });
  },

  // 获取手机号
  getPhoneNum() {
    let url = "/customer/info/getMobilePhone";
    let params = {
      code: this.data.code,
      encryptedData: this.data.encryptedData,
      iv: this.data.iv,
    };
    request
      .http(url, "GET", params, 0)
      .then((res) => {
        let data = res.data.data;
        console.log(res);
        if (res.data.code == 200) {
          wx.setStorageSync("phoneNumber", data);
          this.setData({
            phoneNumber: data,
            showLogin: false,
          });
          this.getOrder();
        }
      })
      .catch((err) => {
        console.error(err);
      });
  },

  // 订单查询
  getOrder() {
    let url = "/order/orderInfo/get-order-no-pay";
    let params = {
      mobilePhone: wx.getStorageSync("phoneNumber") || this.data.phoneNumber,
      parkId: this.data.parkId,
      channelCode: this.data.channelCode,
      // parkId=1475359927982772226&channelCode=13
    };
    request
      .http(url, "GET", params, 0)
      .then((res) => {
        console.log(res);
        let data = res.data.data;
        if (res.data.code == 200) {
          if (data.state == 0) {
            wx.showToast({
              icon: "none",
              title: "手机号不正确，请重新授权登陆",
              success: (res) => {
                wx.clearStorageSync("phoneNumber");
                this.setData({
                  showLogin: true,
                });
              },
            });
          }
          if (data.state == 1) {
            //uuid   == null是待支付订单    ！= null是确认出场信息
            console.log("状态", data.state);
            data.isOutPark == false
              ? this.setData({ buttonState: true })
              : this.setData({ buttonState: false });
            let orderInfo = data.msg[0];
            let totalTime = timeStamp.timeStamp(orderInfo.parkDuration); // 停车时长，改为天时分
            this.setData({
              orderInfo,
              totalTime,
              orderState: true,
            });
          }
        }
      })
      .catch((err) => {
        console.error(err.data);
        if(err.data.desc == "") {
          wx.showToast({
            title: '该停车场暂无出场信息',
            icon:'none'
          })
        }
      });
  },

  // 跳转添加车牌
  toAddCarNumber() {
    wx.navigateTo({
      url: "/pages/licencePlate/licencePlate",
    });
  },

  //确认出场
  confirm() {
    let orderInfo = this.data.orderInfo;
    let data = {
      carNumber: orderInfo.carNumber,
      customerId: orderInfo.customerId,
      inTime: orderInfo.inTime,
      orderCode: orderInfo.orderCode,
      outChannelCode: orderInfo.channelCode,
      paidAmount: orderInfo.paidAmount,
      parkId: orderInfo.parkId,
      uuid: orderInfo.uuid,
    };
    request
      .http("/order/orderInfo/park-out-channel", "GET", data, 0)
      .then((res) => {
        let data = res.data.data;
        if (res.data.code == 200) {
          console.log(data);
          if (data.state == 1) {
            wx.reLaunch({
              url: "../index/index",
            });
          } else if (data.state == 0) {
            console.log(data);
            if (data.errmsg != null) {
              wx.showToast({ icon: "none", title: data.errmsg });
            }
          } else {
            console.log(data);
            // wx.showToast({
            //   icon: 'none',
            //   title: '出场失败，请重新授权',
            // })
          }
        }
      })
      .catch((err) => {
        console.error(err);
      });
  },

  // 取消登陆
  cancelLogin() {
    wx.showModal({
      title: "警告",
      content: "关闭后，请重新授权",
      confirmText: "关闭",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          this.setData({
            orderState: false,
          });
        } else {
          this.setData({
            orderState: false,
          });
        }
      },
    });
  },
});
